<template>
  <div class="notice-container" @click="handleClick">
    <el-badge :value="unreadCount" :max="99" class="notice-badge" :hidden="unreadCount === 0">
      <i class="el-icon-bell"></i>
    </el-badge>

    <!-- 添加授权提示框 -->
    <el-dialog
      title="通知提醒"
      :visible.sync="showAuthDialog"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <div class="auth-content">
        <i class="el-icon-bell warning-icon"></i>
        <p>为了给您提供更好的消息提醒服务，我们需要您授权开启通知提醒功能。</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleReject">暂不开启</el-button>
        <el-button type="primary" @click="handleAllow">同意开启</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUnreadCount } from "@/api/system/message";
import { getConfigKey } from "@/api/system/config";

export default {
  name: 'Notice',
  data() {
    return {
      unreadCount: 0,
      timer: null,
      lastCount: 0,
      notifyConfig: null,
      audioMap: new Map(), // 用于存储预加载的音频
      showAuthDialog: false, // 控制授权弹窗显示
      hasUserInteracted: false // 用户是否已交互
    }
  },
  created() {
    this.initNotifyConfig();
    this.startPolling();
    // 检查是否需要显示授权弹窗
    const authStatus = localStorage.getItem('notificationAuth');
    if (authStatus !== 'allowed') {
      this.showAuthDialog = true;
    } else {
      this.hasUserInteracted = true;
    }
  },
  beforeDestroy() {
    // 组件销毁前清除定时器
    this.clearPolling()
  },
  methods: {
    async initNotifyConfig() {
      try {
        const response = await getConfigKey('sys.notice.soundType');
        this.notifyConfig = response.msg ? JSON.parse(response.msg) : {};
        // 预加载所有音频
        this.preloadAudios();
      } catch (error) {
        console.error('获取通知配置失败:', error);
      }
    },
    // 预加载所有音频文件
    preloadAudios() {
      const audioTypes = ['notify1', 'notify2', 'notify3'];
      audioTypes.forEach(type => {
        const audio = new Audio(require(`@/assets/sounds/${type}.mp3`));
        audio.load(); // 预加载
        this.audioMap.set(type, audio);
      });
    },
    // 检查是否有权限播放声音
    checkSoundPermission() {
      const authStatus = localStorage.getItem('notificationAuth');
      return authStatus === 'allowed';
    },
    // 播放音频
    playNotifySound() {
      if (!this.hasUserInteracted || !this.checkSoundPermission()) {
        return; // 如果用户未交互，不播放声音
      }
      if (this.notifyConfig?.soundEnabled) {
        const audio = this.audioMap.get(this.notifyConfig.soundType);
        if (audio) {
          audio.currentTime = 0;
          const playPromise = audio.play();
          if (playPromise) {
            playPromise.catch(error => {
              console.log('音频播放失败:', error);
              // 如果播放失败，可能需要重新请求授权
              if (error.name === 'NotAllowedError') {
                this.showAuthDialog = true;
              }
            });
          }
        }
      }
    },
    // 用户同意授权
    handleAllow() {
      this.hasUserInteracted = true;
      localStorage.setItem('notificationAuth', 'allowed');
      this.showAuthDialog = false;
      // 播放一次测试音频
      this.playNotifySound();
    },
    // 用户拒绝授权
    handleReject() {
      localStorage.setItem('notificationAuth', 'rejected');
      this.showAuthDialog = false;
    },
    startPolling() {
      this.fetchUnreadMessages()
      this.timer = setInterval(() => {
        this.fetchUnreadMessages()
      }, 30000) // 每5秒轮询一次
    },
    clearPolling() {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
    },
    async fetchUnreadMessages() {
      try {
        const response = await getUnreadCount();
        const newCount = response.data;
        
        if (newCount > 0) {
          this.playNotifySound();
          
          this.$notify({
            title: '新消息提醒',
            message: `您有 ${newCount} 条未读消息`,
            type: 'info',
            duration: this.notifyConfig?.duration || 0,
            showClose: true
          });

          // 使用 Vue 实例上的事件总线
          this.$bus.$emit('refresh-message-data');
          
        } else if (newCount === 0) {
          this.$notify.closeAll();
        }
        
        this.unreadCount = newCount;
        this.lastCount = newCount;
      } catch (error) {
        console.error('获取未读消息失败:', error);
      }
    },
    handleClick() {
      // 点击跳转到消息列表页面
      this.$router.push('/system/message/index')
    }
  }
}
</script>

<style lang="scss" scoped>
.notice-container {
  cursor: pointer;
  padding: 0 10px;
  position: relative;
}

.notice-container i {
  font-size: 20px;
  color: #606266;
}

.notice-container:hover i {
  color: #409EFF;
}

::v-deep .el-badge__content {
  height: 16px;
  line-height: 16px;
  padding: 0 4px;
  border: none;
  font-size: 12px;
  top: 15px;
  right: 0px;
  transform: translateY(-50%) translateX(50%);
}

// 添加全局样式覆盖，调整消息提醒的位置
:global(.el-notification) {
  margin-top: 50px;
}

.auth-content {
  text-align: center;
  padding: 20px 0;

  .warning-icon {
    font-size: 48px;
    color: #E6A23C;
    margin-bottom: 20px;
  }

  p {
    color: #606266;
    font-size: 14px;
    line-height: 1.6;
    margin: 0;
  }
}

.dialog-footer {
  text-align: center;
}
</style>

